import { login, getUserInfo } from '@/api'
import { setToken, getToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    user: JSON.parse(localStorage.getItem('user')) || {
    }
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  REMOVE_TOKEN(state) {
    state.token = ''
    removeToken()
  },
  SET_USERINFO: (state, user) => {
    state.user = { ...state.user, ...user }
    // console.log(state.user)
    localStorage.setItem('user', JSON.stringify(state.user))
  }

}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { data } = await login(userInfo)
    // console.log(data)
    if (data.success) {
      commit('SET_TOKEN', data.token)
      commit('SET_USERINFO', data)
    }

    return data
  },
  async getInfo(store, userId) {
    console.log(userId)
    const { data } = await getUserInfo(userId)
    console.log(data)
    store.commit('SET_USERINFO', data)
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

